#include <Messager.h>
#include <string>
#include <cstring>
#include <iomanip>
#include <DateTime.h>

using namespace std;

Messager::Messager(Socket socket)
{
	this->socket = socket;
}

//接收一条字符串消息
string Messager::recv()
{
	int length;
	if(socket.Recv((char*)&length, 4) > 0)
	{
		char* msg = new char[length];
		socket.Recv(msg, length);
		string ret = string(msg);
		delete msg;
		return ret;
	}else
	{
		throw string("receive msg error!");
	}
}


//发送一条字符串消息
bool Messager::send(string message)
{
	int length = message.size() + 1;
	if(socket.Send((char*)&length, 4) > 0)
	{
		char* msg = new char[length];
		strcpy(msg, message.c_str());
		socket.Send(msg, length);
		delete msg;
	}else
	{
		return false;
	}
	
	return true;
}
 
//格式化一条日志输出
void Messager::log(string type, string msg)
{
	cout << "[" << setw(10) << type << " " << setw(19) << DateTime().toString()  << "]" << msg << endl;
}